using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

public class LoadPrefab : MonoBehaviour
{
    public string prefabPath = "HotRes/PreLoadDll";

    void Start()
    {
#if UNITY_EDITOR
        var go = UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>($"Assets/{prefabPath}.prefab");
        GameObject.Instantiate(go);
#elif UNITY_WEBGL
        StartCoroutine(loadPref());
#else
        var path = $"{prefabPath}.unity3d".ToLower();
        path = $"{Application.streamingAssetsPath}/{path}";
        if (File.Exists(path))
        {
            loadABDone(AssetBundle.LoadFromFile(path));
        }
        else
        {
            Debug.LogError($"dont find :{path}");
        }
#endif
    }

    IEnumerator loadPref()
    {
        yield return 0;
        var path = $"{prefabPath}.unity3d".ToLower();
        var web = UnityWebRequestAssetBundle.GetAssetBundle(
            $"StreamingAssets/{path}?ran={Time.realtimeSinceStartup}");
        yield return web.SendWebRequest();
        Debug.Log("webgl load done");
        var ab = DownloadHandlerAssetBundle.GetContent(web);
        loadABDone(ab);
    }

    void loadABDone(AssetBundle ab)
    {
        var arr = prefabPath.Split("/");
        var prefab = ab.LoadAsset<GameObject>(arr[arr.Length - 1]);
        GameObject.Instantiate(prefab);
        ab.Unload(false);
    }
}